<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8" />
    <title></title>
  </head>

  <body>
    <script>

      //api.github.com
      //www.juhe.cn
      //https://cnodejs.org/api

      //关于异步请求的封装

      //////////////////////////////////////////////////////////////
      //get封装
      function getAjax(url, callback) {
        var ajax;
        if (window.XMLHttpRequest) {
          ajax = new XMLHttpRequest();
        } else {
          ajax = new ActiveXObjext('Microsoft.XMLHttp');
        }
        ajax.open('get', url, true);
        ajax.send(null);
        // ajax.send("page=1&limit=1");//GET 请求这样是否起作用？？
        ajax.onreadystatechange = function () {
          if (ajax.readyState == 4 && ajax.status == 200) {
            var data = ajax.responseText;
            // document.write(data);
            //其他DOM操作
            callback && callback(data);
          }
        };
      }
      //测试
      // var url = 'https://cnodejs.org/api/v1/topics';
      var url = 'https://cnodejs.org/api/v1/topics?page=1&limit=2';
      var showResponseData = function(data){
        console.log(data)
      }
      getAjax(url,showResponseData);//思考：如何利用闭包，通过单例模式避免重复new XMLHttpRequest


      //////////////////////////////////////////////////////////////
      //post封装
      function postAjax(url, requestData,callback) {
        var ajax;
        if (window.XMLHttpRequest) {
          ajax = new XMLHttpRequest();
        } else {
          ajax = new ActiveXObjext('Microsoft.XMLHttp');
        }
        ajax.open('post', url, true);
        // ajax.setRequestHeader("Content-Type", "application/-www-form-urlencoded");
        ajax.send(requestData);
        ajax.onreadystatechange = function () {
          if (ajax.readyState == 4 && ajax.status == 200) {
            var data = ajax.responseText;
            //document.write(data);
            //其他DOM操作
            callback && callback(data);
          }
        };
      }

      // 测试
      var url = 'https://cnodejs.org/api/v1/topics';
      var showResponseData = function(data){
        console.log(data)
      }
      // postAjax(url,null);
      postAjax(url,"key1=value1&key2=value2",showResponseData);


      //思考：如何整合GET和POST ajax 课后连续
      function ajax(method,url,requestData,callback) {
        //...
      }
      //ajax('post',url,"key1=value1&key2=value2",function(){});
    </script>
  </body>
</html>
